import React, { Component } from 'react';
import { connect } from 'dva';
import { withPropsAPI } from "gg-editor";
import { Table, Icon, Spin, Button, Row, Input, Col, Form, Select, Checkbox, Pagination } from 'antd';
import Editor from '@/utils/Editor';
import styles from './index.less';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
const formItemLayout = {
  labelCol: { span: 1 },
  wrapperCol: { span: 20 },
};
import { FormattedMessage } from 'umi-plugin-react/locale';
import {message} from "antd/lib/index";
import editImg from '@/assets/basic/customDictionary/xiazi.png';
import savebuttom from '@/assets/account/robotSetup/savebuttom.png';
import addImg from '@/assets/dialog/add1.png';
import delImg from '@/assets/dialog/del.png';
import moveImg from '@/assets/dialog/start/move.png';
import sy from '@/assets/basic/customDictionary/sy.png';
import bianji from '@/assets/basic/customDictionary/bianji.png';
import edit from '@/assets/basic/customDictionary/edit.png';
import moreImg from '@/assets/knowledge/more.png';
import del1Img from '@/assets/dialog/del1.png';

@connect(({ SpecialCase, dialogCommon, loading }) => ({
  SpecialCase,
  dialogCommon,
  loading: loading.models.data,
}))
class SpecialCase extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      stageId: "",
      specialCaseAdd: false,
      setting: [],
      currentSetting:{
        questions: [],
        retryClearSlots: false,
        answer: "",
        clearSlots: [],
        id: ""
      },
      currentSettingIndex: -1,
      //specialAdd
      addValue:"",
      questions:[],
      slots:[],
      questionIndex:-1,
      content:"",
      dialogId:"",
      robotId:"",
      settingId: "",
      currentPage: 1,
      pageSize: 10,
    };
  }
  componentDidMount() {
    const { currentUser, dialogId, stage } = this.props;
    console.log("dialogId :" + dialogId + ", robotId :" + currentUser.robotId + ", stage :" + stage);
    this.setState({
      robotId: currentUser.robotId,
      dialogId: dialogId,
    },()=>{
      switch (stage){
        case undefined:
          this.getSetting();
          break;
        default:
          this.getInitByStage();
      }
      this.getDialogSlots();
    });
  };

  getSetting = ()=>{
    console.log("qqqqqqqqqqqqqqqqqqqq");
    const { robotId, dialogId } = this.state;
    console.log("robotId: " + robotId + ", dialogId :" + dialogId);
    const { dispatch } = this.props;
    dispatch({
      type: 'specialCase/getSetting',
      payload: {
        _id: "qa",
        robotId: robotId,
        dialogId: dialogId
      },
      callback:(res)=>{
        console.log("全局设置-特殊情况初始值 :" + JSON.stringify(res));
        this.setState({
          settingId: res.settingId,
          setting: res.setting,
        });
      }
    });
  };

  getInitByStage = ()=>{
    console.log("ssssssssssssssssssssssssssssssss");
    const { dialogId, nodeId, stage } = this.state;
    console.log("dialogId: " + dialogId + ", nodeId :" + nodeId + ", stage :" + stage);
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/getStage',
      payload: {
        dialogId: dialogId,
        nodeId: nodeId,
        stage: stage,
        field: "qa",
      },
      callback:(res)=>{
        console.log("收集词槽-特殊情况初始值 :" + JSON.stringify(res));
        this.setState({
          setting: res.dialogStage.qa==null?[]:res.dialogStage.qa,
          stageId: res.dialogStage._id,
        });
      }
    });
  };

  getDialogSlots = ()=>{
    const { dialogId } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/getDialogSlots',
      payload: {
        dialogId: dialogId
      },
      callback:(res)=>{
        this.setState({
          slots: res,
        })
        console.log("词槽列表 :" + JSON.stringify(res));
      }
    });
  };

  addValue = () =>{
    const { currentSetting,addValue } = this.state;
    switch (addValue.trim()){
      case "":
        break
      default:
        currentSetting.questions.push(addValue);
        this.setState({
          currentSetting: currentSetting,
          addValue: "",
        })
    }
  };

  addSlots = (name,index) =>{
    const { addValue,questions,currentSetting } = this.state;
    if(index===-1){
      const newValue = addValue+"<" + name +">";
      this.setState({
        addValue: newValue
      });
    }else{
      const newValue = currentSetting.questions[index]+"<" + name +">";
      console.log("newValue :" + newValue);
      //questions[index] = newValue;
      currentSetting.questions[index] = newValue;
      this.setState({
        currentSetting: currentSetting
      });
    }

    const resemblanceX = `resemblance${index}`;
    this.refs[resemblanceX].focus();
  };

  onChange = (e, type, index) =>{
    switch (type){
      case "a":
        this.setState({
          addValue: e.target.value,
        });
        break
      case "b":
        const { currentSetting } = this.state;
        currentSetting.questions[index] = e.target.value;
        this.setState({
          currentSetting: currentSetting,
        });
        break
    }
  };

  add = () => {
    console.log("添加是stageId ：" + this.state.stageId);
    this.setState({
      specialCaseAdd: true,
      currentSetting:{
        questions: [],
        retryClearSlots: false,
        answer: "",
        clearSlots: [],
        id: Date.parse(new Date()).toString(),
      },
    })
  };

  returnList = () =>{
    this.setState({
      specialCaseAdd: false,
    })
  };

  changeQuestions =(q,i,type)=>{
    const { currentSetting } = this.state;
    switch (type){
      case "del":
        currentSetting.questions.splice(i,1);
        this.setState({
          currentSetting: currentSetting,
        });
        break
      case "up":
        currentSetting.questions.splice(i,1);
        currentSetting.questions.unshift(q);
        this.setState({
          currentSetting: currentSetting,
        });
        break
    }
  };

  changeQuestionsIndex =(i)=>{
    this.setState({
      questionIndex: i,
    });
  };

  cleanSlot = (event) =>{
    const { currentSetting } = this.state
    currentSetting["retryClearSlots"] = !currentSetting["retryClearSlots"]
    this.setState({
      currentSetting: currentSetting,
    })
  };

  changeSlotValue = (val,index) =>{
    const { currentSetting } = this.state
    currentSetting.clearSlots[index] = val;
    this.setState({
      currentSetting: currentSetting,
    });
  };

  addClearSlots = () =>{
    const { currentSetting } = this.state
    currentSetting.clearSlots.push("")
    this.setState({
      currentSetting: currentSetting,
    })
  };

  closeSlot = (index) =>{
    const { currentSetting } = this.state
    currentSetting.clearSlots.splice(index, 1)
    this.setState({
      currentSetting: currentSetting,
    })
  };

  edit = (item,index) =>{
    this.setState({
      currentSetting: item,
      specialCaseAdd: true,
      currentSettingIndex: index,
    });
  };

  save = () =>{
    console.log("currentSettingIndex :" + this.state.currentSettingIndex + ", stageId :" + this.state.stageId);
    if(this.state.stage == undefined){
      this.saveSetting();
    }else{
      this.saveStage();
    }
  };

  saveSetting = () =>{
    const { currentSetting,settingId } = this.state;
    const { dispatch } = this.props;
    const con = `editorRef`;
    if(currentSetting.questions.length <= 0){
      message.info("请至少填写一条相似问");
      return
    }
    if(this.refs[con].getUeditorContent().trim() == ""){
      message.info("问题回复不能为空");
      return
    }
    console.log("answer :" + this.refs[con].getUeditorContent());
    console.log("json :" + JSON.stringify(currentSetting));
    currentSetting["answer"] = this.refs[con].getUeditorContent();

    this.setState({
      currentSetting: currentSetting
    });
    dispatch({
      type: 'specialCase/doAdd',
      payload: {
        index: currentSetting.id,
        data: currentSetting,
        settingId: settingId
      },
      callback:(res)=>{
        console.log("全局设置-特殊情况添加结果 :" + JSON.stringify(res));
        if(res.code == 0){
          message.info("保存成功");
          setTimeout(() => {
            this.setState({
              specialCaseAdd: false,
            }, () =>{
              this.getSetting();
            })
          }, 1500);
        }else{
          message.info("保存失败");
        }
      }
    });
  };

  saveStage = () =>{
    const { setting,stageId,currentSettingIndex,currentSetting } = this.state;
    const { dispatch } = this.props;
    const con = `editorRef`;
    if(currentSetting.questions.length <= 0){
      message.info("请至少填写一条相似问");
      return
    }
    if(this.refs[con].getUeditorContent().trim() === ""){
      message.info("问题回复不能为空");
      return
    }
    currentSetting["answer"] = this.refs[con].getUeditorContent();
    this.setState({
      currentSetting: currentSetting
    });

    if(currentSettingIndex < 0){
      setting.unshift(currentSetting);
    }else{
      setting[currentSettingIndex] = currentSetting;
    }
    this.setState({
      setting: setting
    },() =>{
      dispatch({
        type: 'dialogCommon/saveStage',
        payload: {
          _id: stageId,
          field: "qa",
          qa: setting
        },
        callback:(res)=>{
          if(res.code === 0){
            message.info("保存成功");
            setTimeout(() => {
              this.setState({
                specialCaseAdd: false,
              }, () =>{
                this.getInitByStage();
              })
            }, 1000);
          }else{
            message.info("保存失败");
          }
        }
      });
    });
  };


  deleteQa = (index) =>{
    const { setting,robotId,dialogId,settingId,currentPage,pageSize } = this.state;
    console.log("index :" + index + ",currentPage" + currentPage + ", pageSize:" + pageSize);
    setting.splice((currentPage-1)*pageSize+index ,1);
    const { dispatch } = this.props;
    dispatch({
      type: 'specialCase/doSaveQaList',
      payload: {
        _id: 'qa',
        setting: setting,
        robotId: robotId,
        dialogId: dialogId,
        settingId: settingId
      },
      callback:(res)=>{
        console.log("delete-res :" + JSON.stringify(res));
        if(res.status === 0){
          message.info("删除成功");
          if(currentPage > ((setting.length + pageSize - 1)/pageSize)){
            this.setState({
              currentPage: currentPage-1
            })
          }
          this.getSetting();
        }else{
          message.info("删除失败");
        }
      }
    });
  };

  handleSubmitComment = (val) =>{
    console.log("handleSubmitComment :" + val);
    this.setState({
      currentPage: val,
    })
  };

  changePageSize = (val) =>{
    console.log("changePageSize :" + val);
    this.setState({
      pageSize: val,
    })
  }

  specialList = (type) => {
    const { setting } = this.state;
    const columns = [
      {
        title: '用户问题',
        width: 'calc(60vw)',
        render: (item) => {
          return(
            <div>{item.questions[0]}</div>
          )
        }
      },
      {
        title: '操作',
        align: 'center',
        width: 'calc(20vw)',
        render: (text,item) => {
          // return <div className={styles.pb}>
          //   <div
          //     onClick={() =>this.edit(item,index)}
          //     className={styles.buttongl}>
          //     <MyIcon style={{ marginRight: 5 }} type="icon-bi" />
          //     <FormattedMessage id="app.dialog.question.edit" defaultMessage="Edit" />
          //   </div>
          //   <div
          //     onClick={() =>this.deleteQa(index)}
          //     style={{ marginLeft: 10, background: '#e8313b' }}
          //     className={styles.buttongl}>
          //     <span><Icon size="small" type='delete' style={{ marginRight: 5 }} />
          //     </span><span> <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" /></span>
          //   </div>
          // </div>
          return (
            <div className={styles.pb}>
              <div className={styles.tool}>
                <img onClick={text => {this.edit(item);}} src={bianji} alt="bianji"/>
                <img onClick={text => {this.deleteQa(item);}} style={{ marginLeft: 15 }} src={edit}/>
              </div>
              <img src={moreImg} className={styles.more}/>
            </div>
          );
        }
      }
    ]
    let loading = false;
    return ( //主页
      <div>
        <div>
          {/*<Button type="primary" style={{ marginBottom: '20px'}} onClick={this.add}>添加</Button>*/}
          <img onClick={this.add} src={editImg} style={{ cursor: 'pointer'}} />
        </div>
        <Spin spinning={loading}>
          <div style={{padding:'0 20px'}}>
            <Table
              className="zdyTable"
              columns={columns}
              dataSource={this.state.setting}//数据
              pagination={false}
            />
          </div>

          <Pagination
            style={{ textAlign: 'center', marginTop: 20}}
            total={setting.length}
            current={this.state.currentPage} // 当前页
            showSizeChanger={true} // 是否显示可以设置几条一页的选项
            onChange={this.handleSubmitComment}
            onShowSizeChange={this.changePageSize}
            showTotal={() => `共 ${setting.length} 条`}
          />

        </Spin>
      </div>
    )
  };

  forMapSlotsOption = option =>{
    return (
      <Option value={option.slotId}>{option.slotName}</Option>
    )
  };

  /*currentSetting.clearSlots.map((itemId,index)=>(
    <Select value={itemId} style={{ width: '16%',marginRight:'10px' }} size="small" onChange={(value) => this.changeSlotValue(value,index)}>
    {
      this.state.slots.map((item)=>(
          <Select.Option value={item.id}>{item.name}</Select.Option>
        )
      )
    }
    </Select>
))*/
  forMap = (itemId,index) => {
    const {slots} = this.state;
    const OptionElem = slots.map(this.forMapSlotsOption);
    return (
      <span>
        <Select size='small' value={itemId} defaultValue='none' style={{ width: 120,marginLeft: 15 }} onChange={(value) => this.changeSlotValue(value,index)}>
          <Select.Option value='none'>请选择词槽</Select.Option>
          {OptionElem}
        </Select>
        {/*<Icon type="close-circle" onClick={() =>this.closeSlot(index)} style={{marginLeft:5,cursor:'pointer'}} />*/}

        <img src={del1Img} alt="" height={20} style={{marginLeft:10,cursor:"pointer"}}  onClick={() =>this.closeSlot(index)}  />

      </span>
    );
  };

  specialAdd = () => {
    const { questions,slots,currentSetting } = this.state;
    const tagChild = currentSetting.clearSlots.map((itemId,index)=>this.forMap(itemId,index));
    return (
      <div>
        <div>
          <div style={{marginBottom:'20px', fontSize:'16px',width:'18%',}} onClick={this.returnList}>
            <Icon type="arrow-left" style={{ marginRight: 20,cursor:'pointer'}} /><span>返回列表</span>
          </div>
          <Row>
            <Col  xs={24}>
              <div className={styles.title}>
                <span>用户问题</span>
              </div>
            </Col>
          </Row>

          <div style={{margin: '15px 0px 15px 10px',width:'100%'}}>
            <Input
              style={{ width: '89%' }}
              placeholder="请输入相似问题, 点击回车继续添加"
              className={styles.inputItem1}
              value={this.state.addValue}
              onChange={event=>{this.onChange(event,"a",-1)}}
              onPressEnter={this.addValue}
              onFocus={e=>this.changeQuestionsIndex(-1)}
              ref={`resemblance-1`}
            />
            <img src={addImg} onClick={this.addValue} alt="" height={47}/>
            <div>
              {
                slots.map((slotItem)=>{
                  return (
                    <Button htmlType='button' size="small" style={{marginRight:10}} onClick={() => this.addSlots(slotItem.slotName, -1)}>&lt;{slotItem.slotName}&gt;</Button>
                  )
                })
              }
            </div>
          </div>

          {
            currentSetting.questions.map((q,i)=>{
              return(
                <div style={{width: '100%',margin:'15px 0px 15px 10px'}}>
                  <div className={styles.item}>
                    <Input
                      style={{ width: '89%' }}
                      className={styles.inputItem1}
                      value={q}
                      onChange={event=>{this.onChange(event,"b",i)}}
                      onFocus={e=>this.changeQuestionsIndex(i)}
                      ref={`resemblance${i}`}
                    />
                    <span className={styles.tool}>
                      <img src={moveImg} alt=""  onClick={() => this.changeQuestions(q,i,"up")} className={styles.toolImg} />
                      <img src={delImg} alt="" onClick={() => this.changeQuestions(q,i,"del")} className={styles.toolImg} />
                    </span>
                    <div style={{ marginTop: '3px' }}>
                      {
                        this.state.questionIndex===i?
                          slots.map((slotItem)=>{
                            return (
                              <Button htmlType='button' size="small" style={{marginRight:10}}  onClick={() => this.addSlots(slotItem.slotName, i)}>&lt;{slotItem.slotName}&gt;</Button>
                            )
                          }):null
                      }
                    </div>
                  </div>
                </div>
              )
            })
          }
        </div>

        <div style={{margin:'20px 0px'}}>
          <Row>
            <Col xs={24}>
              <div className={styles.title}>
                <span>问题回复</span>
              </div>
            </Col>
          </Row>
          <div className='fuwenben' style={{ lineHeight: '20px',  zIndex:1,margin: '15px 0px 15px 10px',width:'95%' }}>
            <Editor content={this.state.currentSetting.answer} name="content" id="content" height="300" ref="editorRef" />
        </div>
        </div>

        <div style={{margin:'20px 0px'}}>
          <Row>
            <Col  xs={24}>
              <div className={styles.title}>
                <span style={{ color: '#71a3f1' }}>词槽处理</span>
              </div>
            </Col>
          </Row>
          <Form.Item {...formItemLayout} label="">
            <div style={{marginLeft:10,display:'inline-block',width:'100%'}}>
              <Checkbox style={{width: 120,marginLeft: 15,color:"#222"}} checked={currentSetting.retryClearSlots} onChange={() => this.cleanSlot()}>清空词槽</Checkbox>
              {tagChild}
              <img src={addImg} onClick={this.addClearSlots} style={{marginLeft:15,color:'#fff'}} height={47} alt="" />
              {/*<Button htmlType='button' type="primary" size='small' onClick={this.addClearSlots} style={{marginLeft:15,color:'#fff'}} className={styles.addSlotBtn} >添加词槽</Button>*/}
            </div>
          </Form.Item>

          <div className={styles.flexcen}>
            {/*<Button type="primary" onClick={this.save}>保存</Button>*/}
            <img onClick={this.save} src={savebuttom} />
          </div>
        </div>
        {/*<div style={{margin:'20px 0px'}}>
          <Icon style={{transform: 'rotate(90deg)'}} type="minus"/>词槽处理
          <div style={{margin: '15px 0px 15px 10px'}}>
            <Checkbox style={{marginRight:'10px'}} checked={currentSetting.retryClearSlots} onChange={() => this.cleanSlot()}>清空词槽</Checkbox>
            {
              currentSetting.clearSlots.map((itemId,index)=>(
                <Select value={itemId} style={{ width: '16%',marginRight:'10px' }} size="small" onChange={(value) => this.changeSlotValue(value,index)}>
                  {
                    this.state.slots.map((item)=>(
                        <Select.Option value={item.id}>{item.name}</Select.Option>
                      )
                    )
                  }
                </Select>
              ))
            }
            <Button type="primary" size="small" onClick={this.addClearSlots}>添加</Button>
          </div>
          <div style={{margin: '15px 0px 15px 10px'}}>
            <Button type="primary">保存</Button>
          </div>
        </div>*/}
      </div>
    )
  };

  setSpecialVisible = () => {
    this.props.setSpecialVisible();
  };

  render() {
    const {type} = this.props;
    if(this.state.specialCaseAdd){
      return(
        <div>
          {this.specialAdd()}
        </div>
      )
    }else{
      return (
        <div>
          {this.specialList(type)}
        </div>
      );
    }
  }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(SpecialCase);
